const { db, query } = require("../db")

const officegen = require('officegen')
const fs = require('fs')
const path = require('path')

const SA = require('../utils/StrAndArr')

// 根据问题编号获取具体问题数组
exports.getquestions = async (req, res, next) => {
  const { questionIds } = req.body
  let questions = []
  for (let i = 0; i < questionIds.length; i++) {
    let question = await query(`select * from tb_questions where id=${questionIds[i]};`)
    question[0].options = SA.OptionStrToArr(question[0].options)
    questions.push(question[0])
  }
  res.cc({ questions }, 200)
}

// 获取做题题目
exports.getexercisequestions = async (req, res, next) => {
  // console.log(req.query)
  const { username, type, subject, num, isnew } = req.body
  let recordlist = await query(`select * from tb_records where username='${username}' and type='${type}' and subject='${subject}';`)
  // console.log(recordlist)
  let questions = []
  let answers = []
  let isNew = false
  let questionIds = []
  if (recordlist.length != 0 && isnew == 0) {
    // console.log("111")
    // 恢复做题记录
    // let questionIds = SA.StrToArr(record[0].questionIds)
    // console.log(questionIds)
    for (let i = 0; i < recordlist.length; i++) {
      let question = await query(`select * from tb_questions where id=${recordlist[i].questionId};`)
      question[0].options = SA.OptionStrToArr(question[0].options)
      questions.push(question[0])
      answers.push(recordlist[i].answer)
      questionIds.push(recordlist[i].questionId)
    }
    // console.log(questions)
  } else {
    // console.log("222")
    if (recordlist.length !== 0 && isnew == 1) {
      await query(`delete from tb_records where username='${username}' and type='${type}' and subject='${subject}';`)
    }
    // 新建答题记录
    isNew = true
    let questionlist = await query(`select * from tb_questions where subject='${subject}';`)
    // console.log(questionIds)
    let len = num <= questionlist.length ? num : questionlist.length
    // console.log(len)
    for (let k = 0; k < len; k++) {
      let index = Math.floor(Math.random() * questionlist.length)
      let question = questionlist[index]
      question.options = SA.OptionStrToArr(question.options)
      questions.push(question)
      questionlist.splice(index, 1)
      answers.push('')
      questionIds.push(question.id)
      await query(`insert into tb_records (subject, type, questionId, answer, username) value ('${subject}', '${type}', ${question.id}, '', '${username}');`)
    }
  }
  res.cc({ questions, answers, isNew, questionIds }, 200)
}

// 判断是否存在之前的组卷记录
exports.getgrouprecord = async (req, res, next) => {
  const { username, subject } = req.body
  let list = await query(`select * from tb_records where username='${username}' and subject='${subject}' and type='组卷';`)
  if (list.length == 0) {
    res.cc({
      isExist: false
    }, 200)
  } else {
    res.cc({
      isExist: true
    }, 200)
  }
}

// 新建组卷题目
exports.creategroup = async (req, res, next) => {
  const { username, subject, tiannum, duonum, dannum, pannum } = req.body
  // 删除之前的记录
  await query(`delete from tb_records where username='${username}' and type='组卷' and subject='${subject}';`)
  // 添加填空题
  let tianlist = await query(`select * from view_tian where subject='${subject}';`)
  let tianlength = tianlist.length > tiannum ? tiannum : tianlist.length
  for (let i=0; i<tianlength; i++) {
    let index = Math.floor(Math.random() * tianlist.length)
      let question = tianlist[index]
      tianlist.splice(index, 1)
      await query(`insert into tb_records (subject, type, questionId, answer, username) value ('${subject}', '组卷', ${question.id}, '', '${username}');`)
  }

  // 添加多选题
  let duolist = await query(`select * from view_duo where subject='${subject}';`)
  let duolength = duolist.length > duonum ? duonum : duolist.length
  for (let i=0; i<duolength; i++) {
    let index = Math.floor(Math.random() * duolist.length)
      let question = duolist[index]
      duolist.splice(index, 1)
      await query(`insert into tb_records (subject, type, questionId, answer, username) value ('${subject}', '组卷', ${question.id}, '', '${username}');`)
  }

  // 添加单选题
  let danlist = await query(`select * from view_dan where subject='${subject}';`)
  let danlength = danlist.length > dannum ? dannum : danlist.length
  for (let i=0; i<danlength; i++) {
    let index = Math.floor(Math.random() * danlist.length)
      let question = danlist[index]
      danlist.splice(index, 1)
      await query(`insert into tb_records (subject, type, questionId, answer, username) value ('${subject}', '组卷', ${question.id}, '', '${username}');`)
  }

  // 添加判断题
  let panlist = await query(`select * from view_pan where subject='${subject}';`)
  let panlength = panlist.length > pannum ? pannum : panlist.length
  for (let i=0; i<panlength; i++) {
    let index = Math.floor(Math.random() * panlist.length)
      let question = panlist[index]
      panlist.splice(index, 1)
      await query(`insert into tb_records (subject, type, questionId, answer, username) value ('${subject}', '组卷', ${question.id}, '', '${username}');`)
  }

  res.cc({ msg: '新建组卷成功' }, 200)
}

// 修改做题记录
exports.setrecords = async (req, res, next) => {
  // console.log(req.query)
  const { username, type, subject, answers, questionIds } = req.body
  for (let i = 0; i < questionIds.length; i++) {
    await query(`update tb_records set answer='${answers[i]}' where username='${username}' and type='${type}' and subject='${subject}' and questionId=${questionIds[i]};`)
  }
  res.cc(null, 200)
}

// 获取历史记录列表
exports.gethistorylist = async (req, res, next) => {
  // console.log(req.query)
  const { username, type } = req.query
  let historylist = []
  if (type == '历史记录') {
    historylist = await query(`select distinct time, subject, type from tb_histories where username='${username}';`)
  } else {
    let list = await query(`select distinct time, testtime from tb_testhistories where username='${username}';`)
    for (let i=0; i<list.length; i++) {
      let testpaperlist = await query(`select distinct testpaper from tb_testpapers where time=${list[i].testtime};`)
      historylist.push({
        time: list[i].time,
        testpaper: testpaperlist[0].testpaper
      })
    }
  }
  
  if (historylist.length <= 0) {
    res.cc({
      msg: '暂无历史记录'
    }, 401)
  } else {
    res.cc({ historylist }, 200)
  }
}

// 提交答案
exports.submitanswers = async (req, res, next) => {
  // 提交答案
  const { username, type, subject, questionIds, answers, errorIndexs, grades } = req.body

  let time = Date.now()
  // 删除做题记录和添加历史记录
  for (let i = 0; i < questionIds.length; i++) {
    await query(`delete from tb_records where username='${username}' and type='${type}' and subject='${subject}' and questionId=${questionIds[i]};`)
    await query(`insert into tb_histories (time, subject, type, questionId, username, answer, grade) value (${time}, '${subject}', '${type}', ${questionIds[i]}, '${username}', '${answers[i]}', '${grades[i]}');`)
  }

  // 添加错题
  if (errorIndexs.length != 0) {
    let wronglist = await query(`select * from tb_wrongs where username='${username}';`)

    if (wronglist.length == 0) {
      for (let i = 0; i < errorIndexs.length; i++) {
        await query(`insert into tb_wrongs (username, questionId, answer) value ('${username}', ${questionIds[errorIndexs[i]]}, '${answers[errorIndexs[i]]}');`)
      }
    } else {
      for (let i = 0; i < errorIndexs.length; i++) {
        let flag = false
        for (let k = 0; k < wronglist.length; k++) {
          if (questionIds[errorIndexs[i]] == wronglist[k].questionId) {
            flag = true
            break
          }
        }
        if (flag) {
          await query(`update tb_wrongs set answer='${answers[errorIndexs[i]]}' where username='${username}' and questionId=${questionIds[errorIndexs[i]]};`)
        } else {
          await query(`insert into tb_wrongs (username, questionId, answer) value ('${username}', ${questionIds[errorIndexs[i]]}, '${answers[errorIndexs[i]]}');`)
        }
      }
    }
  }
  // let wrong = await query(`select * from tb_wrongs where username='${username}';`)
  // console.log(wrong)
  res.cc({
    msg: '提交成功',
    time
    // wronglist: wrong
  }, 200)
}

// 获取成绩页面内容
exports.getgrade = async (req, res, next) => {
  // console.log(req.query)
  let { time, type } = req.query
  time = time - 0
  let historylist = []
  if (type == '试卷') {
    historylist = await query(`select * from tb_testhistories where time=${time};`)
  } else {
    historylist = await query(`select * from tb_histories where time=${time};`)
  }
  
  if (historylist.length <= 0) {
    res.cc({
      msg: '无做题记录'
    })
  }
  // console.log(historylist)
  let questions = []
  let grades = []
  let errorIndexs = []
  let answers = []
  let score = 0
  let total = 0
  for (let i = 0; i < historylist.length; i++) {
    let question = await query(`select * from tb_questions where id=${historylist[i].questionId};`)
    question[0].options = SA.OptionStrToArr(question[0].options)
    questions.push(question[0])
    if (questions[i].answer != historylist[i].answer) {
      errorIndexs.push(i)
    }
    answers.push(historylist[i].answer)
    grades.push(historylist[i].grade)
    if (type == '试卷') {
      total += historylist[i].score
      score += historylist[i].score * historylist[i].grade
    } else {
      score += historylist[i].grade
      total ++
    }
  }
  res.cc({
    questions,
    answers,
    errorIndexs,
    grades,
    score,
    total
  }, 200)
}

// 获取错题列表
exports.getwronglist = async (req, res, next) => {
  // console.log(req.query)
  const { username } = req.body
  let wronglist = await query(`select * from tb_wrongs where username='${username}';`)
  // console.log(wronglist)
  if (wronglist.length <= 0) {
    res.cc({
      msg: '无错题记录'
    }, 401)
  } else {
    let results = []
    for (let i = 0; i < wronglist.length; i++) {
      let question = await query(`select * from tb_questions where id=${wronglist[i].questionId};`)
      if (i == 0) {
        results.push({
          subject: question[0].subject,
          questionIds: [question[0].id],
          answers: [wronglist[i].answer]
        })
      } else {
        let flag = false
        // 判断是否属于相同科目
        for (let k = 0; k < results.length; k++) {
          if (question[0].subject == results[k].subject) {
            results[k].questionIds.push(question[0].id)
            results[k].answers.push(wronglist[i].answer)
            flag = true
            break
          }
        }
        // 错题属于不同科目
        if (!flag) {
          results.push({
            subject: question[0].subject,
            questionIds: [question[0].id],
            answers: [wronglist[i].answer]
          })
        }
      }
    }
    // console.log(results)
    res.cc({
      wronglist: results
    }, 200)
  }
}

// 获取收藏列表
exports.getcollectlist = async (req, res, next) => {
  const { username } = req.body
  let list = await query(`select * from tb_collects where username='${username}';`)
  if (list.length <= 0) {
    res.cc({
      msg: '无收藏记录'
    }, 401)
  } else {
    let collectlist = []
    for (let i = 0; i < list.length; i++) {
      if (i == 0) {
        collectlist.push({
          foldername: list[0].foldername,
          questionIds: [list[0].questionId]
        })
      } else {
        let flag = false
        for (let k = 0; k < collectlist.length; k++) {
          if (list[i].foldername == collectlist[k].foldername) {
            collectlist[k].questionIds.push(list[i].questionId)
            flag = true
            break
          }
        }
        if (!flag) {
          collectlist.push({
            foldername: list[i].foldername,
            questionIds: [list[i].questionId]
          })
        }
      }
    }
    res.cc({
      collectlist
    }, 200)
  }
}

// 获取收藏题目
exports.getcollectquestions = async (req, res, next) => {
  const { username, foldername } = req.body
  // console.log(req.body)

  let list = await query(`select * from tb_collects where username='${username}' and foldername='${foldername}';`)
  // console.log(list)
  if (list.length <= 0) {
    res.cc({
      msg: '无收藏记录'
    }, 401)
  } else {
    let questions = []
    for (let i = 0; i < list.length; i++) {
      let question = await query(`select * from tb_questions where id=${list[i].questionId};`)
      question[0].options = SA.OptionStrToArr(question[0].options)
      questions.push(question[0])
    }
    res.cc({
      questions
    }, 200)
  }
}

// 取消收藏
exports.delcollectquestions = async (req, res, next) => {
  const { username, foldername, cancalIds } = req.body
  console.log(req.body)

  let list = await query(`select * from tb_collects where username='${username}' and foldername='${foldername}';`)
  // console.log(list)
  if (list.length <= 0) {
    res.cc({
      msg: '取消收藏失败'
    }, 401)
  } else {
    for (let i = 0; i < cancalIds.length; i++) {
      await query(`delete from tb_collects where username='${username}' and foldername='${foldername}' and questionId=${cancalIds[i]};`)
    }
    res.cc({
      msg: '修改成功'
    }, 200)
  }
}

// 添加收藏
exports.addcollectquestion = async (req, res, next) => {
  const { username, foldername, questionId } = req.body
  // console.log(req.body)
  let sql = `insert into tb_collects (username, foldername, questionId) value ('${username}', '${foldername}', ${questionId});`
  db.query(sql, function (err, results) {
    if (err) {
      // console.log('登陆失败')
      return res.cc({ msg: '收藏夹已存在' })
    }
    res.cc({
      msg: '添加成功'
    }, 200)
  })
}

// 获取评论列表
exports.getcommentlist = async (req, res, next) => {
  const { questionId } = req.query
  // console.log(req.query)
  let commentlist = await query(`select * from tb_comments where questionId=${questionId};`)
  for (let i = 0; i < commentlist.length; i++) {
    let namelist = await query(`select * from tb_users where username='${commentlist[i].username}'`)
    commentlist[i].name = namelist[0].name
    commentlist[i].imgurl = namelist[0].imgurl
  }
  res.cc({
    commentlist
  }, 200)
}

// 添加评论
exports.addcomment = async (req, res, next) => {
  const { questionId, username, comment } = req.body
  // console.log(req.query)
  let commentlist = await query(`select * from tb_comments where questionId=${questionId} and username='${username}';`)
  if (commentlist.length == 0) {
    await query(`insert into tb_comments (username, comment, questionId, isreport) value ('${username}', '${comment}', ${questionId}, 0);`)
  } else {
    await query(`update tb_comments set comment='${comment}' where username='${username}' and questionId=${questionId};`)
  }
  res.cc({
    msg: '添加成功'
  }, 200)
}

// 获取问题列表
exports.getquestionlist = async (req, res, next) => {
  const { param } = req.query
  let questionlist = await query(`select * from tb_questions;`)
  let subjectlist = await query(`select * from view_subjects;`)
  let list = []
  for (let i = 0; i < questionlist.length; i++) {
    if (questionlist[i].title.indexOf(param) !== -1 || questionlist[i].answer.indexOf(param) !== -1 || questionlist[i].analysis.indexOf(param) !== -1 || (questionlist[i].options && questionlist[i].options.indexOf(param) !== -1)) {
      questionlist[i].options = SA.OptionStrToArr(questionlist[i].options)
      list.push(questionlist[i])
    }
  }
  res.cc({ questionlist: list, subjectlist }, 200)
}

// 获取科目列表
exports.getsubjectlist = async (req, res, next) => {
  let subjectlist = await query(`select * from view_subjects;`)
  res.cc({ subjectlist }, 200)
}

// 修改/添加问题
exports.setquestion = async (req, res, next) => {
  let { id, title, subject, newsubject, type, options, answer, analysis, isaddsubject } = req.body
  subject = isaddsubject ? newsubject : subject
  options = type == 'tian' ? '' : SA.OptionArrToStr(options)
  let questionlist = await query(`select * from tb_questions where id=${id};`)
  if (questionlist.length == 0) {
    // 添加问题
    await query(`insert into tb_addquestions (title, subject, type, options, answer, analysis) value ('${title}', '${subject}', '${type}', '${options}', '${answer}', '${analysis}');`)
    res.cc({
      msg: '添加成功'
    }, 200)
  } else {
    // 修改问题
    await query(`update tb_questions set title='${title}', subject='${subject}', type='${type}', options='${options}', answer='${answer}', analysis='${analysis}' where id=${id};`)
    res.cc({
      msg: '修改成功'
    }, 200)
  }
}

// 删除问题
exports.delquestion = async (req, res, next) => {
  const { id } = req.body
  let questionlist = await query(`select * from tb_questions where id=${id};`)
  if (questionlist.length !== 0 ) {
    // 删除用户信息
    await query(`delete from tb_questions where id=${id};`)
    res.cc({
      msg: '删除成功'
    }, 200)
  } else {
    res.cc({
      msg: '无此题目'
    })
  }
}

// 获取添加问题列表
exports.getaddquestionlist = async (req, res, next) => {
  const { param } = req.query
  let questionlist = await query(`select * from tb_addquestions;`)
  let subjectlist = await query(`select distinct subject from tb_addquestions;`)
  let list = []
  for (let i = 0; i < questionlist.length; i++) {
    if (questionlist[i].title.indexOf(param) !== -1 || questionlist[i].answer.indexOf(param) !== -1 || questionlist[i].analysis.indexOf(param) !== -1 || (questionlist[i].options && questionlist[i].options.indexOf(param) !== -1)) {
      questionlist[i].options = SA.OptionStrToArr(questionlist[i].options)
      list.push(questionlist[i])
    }
  }
  res.cc({ questionlist: list, subjectlist }, 200)
}

// 修改/添加问题
exports.setaddquestion = async (req, res, next) => {
  let { id, title, subject, newsubject, type, options, answer, analysis, isaddsubject, isadd } = req.body
  subject = isaddsubject ? newsubject : subject
  options = type == 'tian' ? '' : SA.OptionArrToStr(options)
  if (isadd) {
    // 添加问题
    await query(`insert into tb_questions (title, subject, type, options, answer, analysis) value ('${title}', '${subject}', '${type}', '${options}', '${answer}', '${analysis}');`)
    await query(`delete from tb_addquestions where id=${id};`)
    res.cc({
      msg: '添加成功'
    }, 200)
  } else {
    // 修改问题
    await query(`update tb_addquestions set title='${title}', subject='${subject}', type='${type}', options='${options}', answer='${answer}', analysis='${analysis}' where id=${id};`)
    res.cc({
      msg: '修改成功'
    }, 200)
  }
}

// 删除问题
exports.deladdquestion = async (req, res, next) => {
  const { id } = req.body
  let questionlist = await query(`select * from tb_addquestions where id=${id};`)
  if (questionlist.length !== 0 ) {
    // 删除用户信息
    await query(`delete from tb_addquestions where id=${id};`)
    res.cc({
      msg: '删除成功'
    }, 200)
  } else {
    res.cc({
      msg: '无此题目'
    })
  }
}

// 返回问题文档路径
exports.downloadtext = async (req, res, next) => {
  const { questionIds, type, subject, testpaper, scores } = req.body
  const docx = officegen('docx')

  let title = docx.createP({ align: 'center' })
  if (testpaper) {
    title.addText(`${testpaper}`, {bold: true})
  } else {
    title.addText(`${subject}${type}`, {bold: true})
  }
  
  
  title = docx.createP({ align: 'left' })
  for (let i=0; i<questionIds.length; i++) {
    let question = await query(`select * from tb_questions where id=${questionIds[i]};`)
    let type = ''
    switch(question[0].type) {
      case 'dan': 
        type = '单选'
        break
      case 'duo': 
        type = '多选'
        break
      case 'tian': 
        type = '填空'
        break
      case 'pan': 
        type = '判断'
        break        
    }
    if (testpaper) {
      title.addText(`（${scores[i]}分）${type}${i+1}：${question[0].title}`)
    } else {
      title.addText(`（${type}）问题${i+1}：${question[0].title}`)
    }
    title.addLineBreak() // 换行
    if (question[0].type != 'tian') {
      let options = SA.OptionStrToArr(question[0].options)
      for (let k=0; k<options.length; k++) {
        title.addText(`\t${options[k].code}. ${options[k].option}`)
        title.addLineBreak() // 换行
      }
    }
    title.addLineBreak() // 换行
  }
  // 获取文件名
  const fileName = 'questionlist.docx'
  // 导出word
  const filePath = path.join(__dirname,'../public/', fileName)
  const out = fs.createWriteStream(filePath)
  // 文件写入
  out.on('error', function (err) {
    return err
  })
  // 生成word
  docx.generate(out)
  res.cc({
    msg: '获取成功'
  }, 200)
}

// 删除收藏夹
exports.delcollectfolder = async (req, res, next) => {
  const { username, foldername } = req.body
  let list = await query(`select * from tb_collects where username='${username}' and foldername='${foldername}';`)
  if (list.length !== 0 ) {
    // 删除用户信息
    await query(`delete from tb_collects where username='${username}' and foldername='${foldername}';`)
    res.cc({
      msg: '删除成功'
    }, 200)
  } else {
    res.cc({
      msg: '无此收藏夹'
    })
  }
}

// 获取全部试卷列表
exports.getalltestpaperlist = async (req, res, next) => {
  const { param  } = req.query
  let subjectlist = await query(`select distinct subject from tb_testpapers;`)
  let arr = []
  for (let j=0; j<subjectlist.length; j++) {
    arr.push(subjectlist[j].subject)
  }
  subjectlist = arr
  let timelist = await query(`select distinct time from tb_testpapers;`)
  let list = []
  for (let i = 0; i < timelist.length; i++) {
      let testpaperlist = await query(`select * from tb_testpapers where time=${timelist[i].time};`)
      if (testpaperlist[0].testpaper.indexOf(param) !== -1) {
        list.push({
          subject: testpaperlist[0].subject,
          testpaper: testpaperlist[0].testpaper,
          questionIds: [],
          scores: [],
          time: testpaperlist[0].time
        })
        for (let k=0; k<testpaperlist.length; k++) {
          list[list.length-1].questionIds.push(testpaperlist[k].questionId)
          list[list.length-1].scores.push(testpaperlist[k].score)
        }
      }
  }
  res.cc({ testpaperlist: list, subjectlist }, 200)
}

// 修改试卷
exports.settestpaper = async (req, res, next) => {
  let { subject, testpaper, questionlist, time = Date.now() } = req.body
  let list = await query(`select testpaper from tb_testpapers where time=${time};`)
  if (list.length !== 0) {
    await query(`delete from tb_testpapers where time=${time};`)
  }
  for (let i=0; i<questionlist.length; i++) {
    await query(`insert into tb_testpapers (time, subject, testpaper, questionId, score) value (${time}, '${subject}', '${testpaper}', ${questionlist[i].id}, ${questionlist[i].score});`)
  }
  res.cc({
    msg: '修改成功'
  }, 200)
}

// 删除试卷
exports.deltestpaper = async (req, res, next) => {
  let { time, subject, testpaper } = req.body
  let list = await query(`select testpaper from tb_testpapers where subject='${subject}' and testpaper='${testpaper}' and time=${time};`)
  if (list.length !== 0) {
    await query(`delete from tb_testpapers where subject='${subject}' and testpaper='${testpaper}' and time=${time};`)
    res.cc({
      msg: '删除成功'
    }, 200)
  } else {
    res.cc({
      msg: '删除失败，查询不到此记录'
    })
  }
}

// 获取某个科目试卷
exports.gettestpaperlist = async (req, res, next) => {
  const { subject  } = req.query
  let testpaperlist = await query(`select distinct time, testpaper from tb_testpapers where subject='${subject}';`)
  // let testpaperlist = []
  // console.log(subject, testpaperlist)
  res.cc({ testpaperlist }, 200)
}

// 获取试卷题目
exports.gettestquestions = async (req, res, next) => {
  // console.log(req.query)
  const { username, time, isnew } = req.body
  // console.log(req.body)
  let questions = []
  let answers = []
  let questionIds = []
  let isNew = false
  let scores = []
  let recordlist = await query(`select * from tb_testrecords where username='${username}' and time=${time};`)
  if (recordlist.length == 0 || isnew == '1') {
    // console.log("新建")
    // 新建做题记录
    isNew = true
    if (isnew && recordlist.length !== 0) {
      // 删除原先记录
      await query(`delete from tb_testrecords where username='${username}' and time=${time};`)
    }
    let list = await query(`select * from tb_testpapers where time=${time};`)
    for (let k = 0; k < list.length; k++) {
      let questionlist = await query(`select * from tb_questions where id=${list[k].questionId};`)
      questionlist[0].options = SA.OptionStrToArr(questionlist[0].options)
      questions.push(questionlist[0])
      answers.push('')
      questionIds.push(questionlist[0].id)
      scores.push(list[k].score)
      await query(`insert into tb_testrecords (username, time, questionId, answer, score) value ('${username}', ${time},  ${questionlist[0].id}, '', ${list[k].score});`)
    }
  } else {
    // 恢复做题记录
    // console.log("恢复")
    for (let i = 0; i < recordlist.length; i++) {
      let questionlist = await query(`select * from tb_questions where id=${recordlist[i].questionId};`)
      questionlist[0].options = SA.OptionStrToArr(questionlist[0].options)
      questions.push(questionlist[0])
      answers.push(recordlist[i].answer)
      questionIds.push(recordlist[i].questionId)
      scores.push(recordlist[i].score)
    }
  }
  res.cc({ questions, answers, questionIds, isNew, scores }, 200)
}

// 修改试卷做题记录
exports.settestrecords = async (req, res, next) => {
  const { username, time, answers, questionIds } = req.body
  // console.log(req.body)
  for (let i = 0; i < questionIds.length; i++) {
    await query(`update tb_testrecords set answer='${answers[i]}' where username='${username}' and time=${time} and questionId=${questionIds[i]};`)
  }
  res.cc(null, 200)
}

// 提交试卷
exports.submittestpaper = async (req, res, next) => {
  const { username, questionIds, answers, errorIndexs, grades, time, scores } = req.body

  let nowTime = Date.now()
  // 删除做题记录和添加历史记录
  for (let i = 0; i < questionIds.length; i++) {
    await query(`delete from tb_testrecords where username='${username}' and time=${time} and questionId=${questionIds[i]};`)
    await query(`insert into tb_testhistories (time, questionId, testtime, username, answer, grade, score) value (${nowTime}, ${questionIds[i]}, ${time}, '${username}', '${answers[i]}', ${grades[i]}, ${scores[i]});`)
  }

  // 添加错题
  if (errorIndexs.length != 0) {
    let wronglist = await query(`select * from tb_wrongs where username='${username}';`)

    if (wronglist.length == 0) {
      for (let i = 0; i < errorIndexs.length; i++) {
        await query(`insert into tb_wrongs (username, questionId, answer) value ('${username}', ${questionIds[errorIndexs[i]]}, '${answers[errorIndexs[i]]}');`)
      }
    } else {
      for (let i = 0; i < errorIndexs.length; i++) {
        let flag = false
        for (let k = 0; k < wronglist.length; k++) {
          if (questionIds[errorIndexs[i]] == wronglist[k].questionId) {
            flag = true
            break
          }
        }
        if (flag) {
          await query(`update tb_wrongs set answer='${answers[errorIndexs[i]]}' where username='${username}' and questionId=${questionIds[errorIndexs[i]]};`)
        } else {
          await query(`insert into tb_wrongs (username, questionId, answer) value ('${username}', ${questionIds[errorIndexs[i]]}, '${answers[errorIndexs[i]]}');`)
        }
      }
    }
  }
  res.cc({
    msg: '提交成功',
    time: nowTime
  }, 200)
}